package com.refuel.component;

import com.refuel.utils.StringTools;
import org.apache.commons.io.IOUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

/**
 * @author zhanghao
 * @description
 * @date 2024/4/18 13:30
 **/
@Component
public class IpSearcher {

    private static final Logger logger = LoggerFactory.getLogger(IpSearcher.class);

    /**
     * searcher 对象
     */
    private Searcher searcher = null;

    /**
     * 初始化 searcher 对象
     */
    public IpSearcher() {
        try {
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource resource = resolver.getResource("ip2region.xdb");
            if (!resource.exists()) {
                throw new Exception("ip2region 文件不存在");
            }

            searcher = Searcher.newWithBuffer(IOUtils.toByteArray(resource.getInputStream()));
            logger.info("IpSearcher 初始化成功");
        } catch (Exception e) {
            logger.error("IpSearcher 初始化异常: ", e);
        }
    }

    /**
     * 根据 ip 地址查询所在地区
     * @param ip ip 地址
     * @return 所在地区
     */
    public String ipSearch(String ip) {
        String province = "未知ip";
        try {
            String region = searcher.search(ip);
            logger.info("ipSearch ip={} region={}", ip, region);

            province = StringTools.splitGetString(region, "|", 2);
        } catch (Exception e) {
            logger.error("ip2region error: ", e);
            return province;
        }

        logger.info("ipSearch ip={} province={}", ip, province);
        return province;
    }
}
